package com.itheima.score.service.impl;

import com.itheima.score.entity.ResponseResult;
import com.itheima.score.mapper.KsClassMapper;
import com.itheima.score.mapper.UserMapper;
import com.itheima.score.pojo.KsClass;
import com.itheima.score.pojo.User;
import com.itheima.score.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Name UserServiceImpl
 * @Author BaiXin
 * @Date 2022-10-25 17:15
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    KsClassMapper ksClassMapper;

    @Override
    public ResponseResult findByMobile(String mobile) {
        //判断参数为空
        if (StringUtils.isEmpty(mobile)) {
            return new ResponseResult(1, "参数有误", null);
        }
        User user = userMapper.findByMobile(mobile);
        //如果用户为空
        if (user == null) {
            return new ResponseResult(1, "用户不存在", null);
        }

        //判断是老师还是学生
        if (user.getRoleId() != null && user.getRoleId().equals(1)) {
            //老师 => 查询班级列表
            List<KsClass> classList = ksClassMapper.findAll();

            return new ResponseResult(0, "查询成功", classList);
        } else if (user.getRoleId().equals(2)) {
            //学生 返回
            List<User> userList = userMapper.findList(mobile);

            return new ResponseResult(0, "操作成功", "学生账户");
        } else {
            return new ResponseResult(1, "未知", null);
        }

    }

    @Override
    public ResponseResult login(User user) {

        //判断传入的参数为空就返回
        if (user == null) {
            return new ResponseResult(1, "空", null);
        }
        //不为空 调用mapper查询数据库
        User LoginUser = userMapper.findByMobileAndPassword(user);
        //查询为空。返回
        if (LoginUser != null) {
            return new ResponseResult(1, "空", null);
        }
        return new ResponseResult(0, "操作成功", null);

    }

    @Override
    public ResponseResult findAll() {
        List<User> userList = userMapper.findAll();

        return new ResponseResult(0, "操作成功", userList);
    }

    @Override
    public ResponseResult findByClassId(Integer classId) {

        List<User> userList = userMapper.findByClassId(classId);
        return new ResponseResult(0, "操作成功", userList);
    }

    @Override
    public ResponseResult addIntegral(User user) {

        int i = userMapper.updateById(user);
        if (i > 0) {
            return new ResponseResult(0, "操作成功", "添加积分成功");
        } else {
            return new ResponseResult(1, "未知错误", null);
        }
    }

}
